﻿using System;
using System.Security.Principal;
using System.Web.Security;
using System.Web.UI;
using Cognitum.Dominio.Aplicacion.Seguridad;
using log4net;
using Karma.Framework.Core.IoC;
using Ctx = Karma.Framework.Core.Security.Context;
using System.Web;
using Karma.Framework.Core;

namespace Cognitum.Presentacion
{
    public partial class LogIn : Page
    {
        private static ILog LOG = LogManager.GetLogger(typeof(LogIn));

        protected void Page_Load(object sender, EventArgs e)
        {
            lblMessage.Visible = false;
            var service = IoCFactory.Resolve<IUsuarioService>();
            if (IsPostBack)
            {
                try
                {
                    if (LOG.IsDebugEnabled)
                    {
                        LOG.Debug(string.Format(
                            "Trying to authenticate user: {0} with domain: {1}, at {2}",
                            txtUsuario.Text, txtUbicacion.Text, DateTime.Now));
                    }
                    var usuario = service.IniciaSesion(txtUsuario.Text, txtPassword.Text,
                        txtUbicacion.Text);
                    if (LOG.IsDebugEnabled)
                    {
                        LOG.Debug(string.Format("User [{0}] authenticated!!! [{1}]",
                            usuario.Username, DateTime.Now));
                    }
                    usuario.Identity = new GenericIdentity(usuario.Ubicacion.Nombre + '\\' +
                        usuario.Username);

                    if (chkRecordar.Checked)
                    {
                        var cookie = new HttpCookie("__login")
                                         {
                                             Expires = DateTime.Now.AddYears(1),
                                             Path = "/",
                                             Name = "__login",
                                             HttpOnly = true
                                         };
                        cookie["Usuario"] = txtUsuario.Text;
                        cookie["Password"] = usuario.Password.Password;
                        cookie["Ubicacion"] = txtUbicacion.Text;
                        Response.Cookies.Add(cookie);
                        if (LOG.IsDebugEnabled)
                        {
                            LOG.Debug("LogIn cookie added.");
                        }
                    }
                    else
                    {
                        var cookie = new HttpCookie("__login")
                        {
                            Expires = DateTime.Now.AddDays(-1),
                            Path = "/",
                            Name = "__login",
                            HttpOnly = true
                        };
                        Response.Cookies.Add(cookie);
                    }
                    if (LOG.IsDebugEnabled)
                    {
                        LOG.Debug(string.Format("Setting up authentication for identity! [{0}]",
                            usuario.Identity.Name));
                    }

                    FormsAuthentication.SetAuthCookie(usuario.Identity.Name, false);
                    Response.Redirect(FormsAuthentication.GetRedirectUrl(txtUsuario.Text, true), false);
                }
                catch(SecurityException ex)
                {
                    lblMessage.Text = ex.Message;
                    lblMessage.Visible = true;
                }
                catch (Exception err)
                {
                    LOG.Error(err);
                }
            }
            else
            {
                if (!String.IsNullOrEmpty(Request["x"]))
                {
                    if (LOG.IsDebugEnabled)
                    {
                        LOG.Debug("Log out user.");
                    }
                    service.CierraSesion();
                    FormsAuthentication.SignOut();
                    Response.Redirect(FormsAuthentication.LoginUrl, true);
                }
                else
                {
                    if (LOG.IsDebugEnabled)
                    {
                        LOG.Debug("Reading cookie from client request.");
                    }
                    var cookie = Request.Cookies["__login"];
                    if (cookie != null)
                    {
                        txtUsuario.Text = cookie["Usuario"];
                        txtPassword.Text = cookie["Password"];
                        txtUbicacion.Text = cookie["Ubicacion"];
                        if (LOG.IsDebugEnabled)
                        {
                            LOG.Debug("Cookie readed.");
                        }
                    }
                    else
                    {
                        if (LOG.IsDebugEnabled)
                        {
                            LOG.Debug("There is no cookie.");
                        }
                    }
                }
            }
        }
    }
}
